<template>
  <el-row class="bg">
    <el-col :span="8" :offset="8">
      <div class="login-wrap">
        <div class="login-container">
          <h2 class="title">{{ title }}</h2>
          <div v-show="!showSlidePicVerify">
            <PwdComp v-show="loginType === 0" :loading="loading" @login="handleLogin" />
            <SmsComp v-show="loginType === 1" :loading="loading" @login="handleLogin" />
            <TbarComp @changeType="type => (loginType = type)" />
          </div>
          <SlidePicVerify ref="refSlidePicVerify" v-show="showSlidePicVerify" @success="login" />
        </div>
      </div>
    </el-col>
  </el-row>
</template>
<script setup lang="ts">
import { computed, ref } from 'vue'
import SlidePicVerify from '@/components/slide-verify/SlideVerify.vue'
import PwdComp from './Pwd.vue'
import SmsComp from './Sms.vue'
import TbarComp from './Tbar.vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { token, env } from '@/utils'

const router = useRouter()
const route = useRoute()

const loading = ref(false)
const loginType = ref(0)

const title = computed(() => import.meta.env.VITE_APP_TITLE)

const enabledSlidePicVerify = computed(() => env.LOGIN_VERIFY == 1)

const refSlidePicVerify = ref()
const showSlidePicVerify = ref(false)

let loginObject: any
const handleLogin = (data: any) => {
  loginObject = data
  if (enabledSlidePicVerify.value) {
    showSlidePicVerify.value = true
  } else {
    login()
  }
}
const resetSlidePicVerify = () => {
  if (enabledSlidePicVerify.value) {
    refSlidePicVerify.value.refresh()
    showSlidePicVerify.value = false
  }
}
const login = () => {
  loading.value = true
  loginObject
    .loginFn(loginObject.loginData)
    .then((resp: any) => {
      if (resp.success) {
        token.set(resp.data)
        router.push({ path: (route.query.redirect || '/') as string })
      } else {
        loading.value = false
        ElMessage.error(resp.message)
        resetSlidePicVerify()
      }
    })
    .catch(() => {
      loading.value = false
      resetSlidePicVerify()
    })
}
</script>
<style lang="scss" scoped>
.bg {
  min-height: 100%;
  background-image: url('../../assets/images/login-bg.jpg');
  background-repeat: no-repeat;
  background-size: cover;
}
.login-wrap {
  height: 100vh;
  padding-top: 30%;
}
.login-container {
  background-color: #fafafa;
  border-radius: 1rem;
  box-shadow: $--box-shadow-base;
  padding: 4rem 3.5rem;

  .title {
    margin: 0px auto 3rem auto;
    text-align: center;
  }
}
</style>
